package zy.vo.sys;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import zy.entity.sys.menu.T_Sys_Menu;
import zy.entity.sys.role.T_Sys_RoleMenu;
import zy.util.StringUtil;

public class RoleMenuVO {
	public static String buildMenuTree(List<T_Sys_Menu> list,List<T_Sys_RoleMenu> existMenu){
		Set<String> existMnCodes = new HashSet<String>();
		if (existMenu != null && existMenu.size() > 0) {
			for (T_Sys_RoleMenu item : existMenu) {
				existMnCodes.add(item.getRm_mn_code());
			}
		}
		StringBuffer treeHtml = new StringBuffer();
		treeHtml.append("[{id:'',name:'所有菜单',open:true},");
		String nodes = "";
		if (list != null && list.size() > 0) {
			nodes = (initMenuToTree(list, "", existMnCodes));
		}
		treeHtml.append(nodes);
		treeHtml.deleteCharAt(treeHtml.length() - 1);
		treeHtml.append("]");
		return treeHtml.toString();
	}
	public static String initMenuToTree(List<T_Sys_Menu> list, String root_code,Set<String> existMnCodes){
		StringBuffer json = new StringBuffer(""); 
		List<T_Sys_Menu> nodeList = hasMenuChild(list, root_code); // 获得集合中的父节点下的子集list  mn_IsHaveChildMenuItem
		list.remove(nodeList);
		// 循环子集
		//json.append("{");
		for (T_Sys_Menu node : nodeList) {
			List<T_Sys_Menu> Nodes = hasMenuChild(list, node.getMn_code());
			json.append("{id:'" + node.getMn_code() + "',pId:'"+node.getMn_upcode()+"',name:'"+node.getMn_name()+"'");
			json.append(",mn_limit:'").append(StringUtil.trimString(node.getMn_limit())).append("'");
//			if (Nodes.size() > 0) {
//				json.append(",open:true");
//			}
			if(existMnCodes.contains(node.getMn_code())){
				json.append(",checked:true");
			}
			json.append("},");
			// 查询全部集合下，是否存在该子集OID的子子集
			if (Nodes.size() > 0) {
				json.append(initMenuToTree(list, node.getMn_code(), existMnCodes)); // 递归树，传入子子集，子集父节点
			}
		}
		return json.toString();
	}
	
	public static List<T_Sys_Menu> hasMenuChild(List<T_Sys_Menu> list,String upcode) {
		List<T_Sys_Menu> nodeList = new ArrayList<T_Sys_Menu>();
		for (T_Sys_Menu comm : list) {
			// 如果数据的父节点==Parent的值，则该数据为子节点，存入list<SysRole>
			if (StringUtil.trimString(comm.getMn_upcode()).equals(upcode)) {
				nodeList.add(comm);
			}
		}
		return nodeList;
	}
}
